import Mock from 'mockjs';
import qs from 'query-string';
import dayjs from 'dayjs';
import setupMock from '@/utils/setupMock';

const { list } = Mock.mock({
  'list|100': [
    {
      _id: /[0-9]{8}[-][0-9]{4}/,
      name: () =>
        Mock.Random.pick([
          '每日推荐视频集',
          '抖音短视频候选集',
          '国际新闻集合',
        ]),
      'articleNum|0-2': 0,
      'createTime|1-60': 0,
      'updateTime|1-60': 0,
    },
  ],
});



setupMock({
  setup: () => {
    Mock.mock(new RegExp('/api/categories'), 'get', (params) => {
      const pageDate = JSON.parse(params.body)
      const p = pageDate.page as number;
      const ps = pageDate.pageSize as number;

      return {
        code: 200,
        msg: '请求成功',
        data: {
          list: list.slice((p - 1) * ps, p * ps),
          total: list.length,
        }
      };
    });

    Mock.mock(new RegExp('/api/categories'), 'post', (params) => {

      const body = qs.parseUrl(params.body);
      const name = JSON.parse(body.url).name
      const data = Mock.mock({
        '_id': /[0-9]{8}[-][0-9]{4}/,
        name,
        articleNum: 0,
        'createTime|1-60': 0,
        'updateTime|1-60': 0,
      })
      list.unshift(data)
      return {
        code: 200,
        msg: '添加成功',
        data
      };
    });

    Mock.mock(new RegExp('/api/categories'), 'delete', (params) => {
      const _id = params.body
      const index = list.findIndex(item => item._id === _id);
      list.splice(index, 1)
      return {
        code: 200,
        msg: '删除成功',
        data: {}
      };
    });

    Mock.mock(new RegExp('/api/categories'), 'put', (params) => {
      const data = JSON.parse(params.body)
      const index = list.findIndex(item => item._id === data._id);
      list[index] = data
      return {
        code: 200,
        msg: '编辑成功',
        data: {}
      };
    });
  },
});
